


#include "PsFrameDemuxer.h"
#include <iostream>
#include <cstdint> 

#include "ParseH264.h"
#include "FileHelp.h"
#include "pcapParse.h"



static int g_ps_frame_my = 0;
static int g_ps_frame_other = 0;
static int g_OnAudioFrame_count = 0;


static uint8_t s_packet[2 * 1024 * 1024];



class PSFrameDemuxerCallbackImp :public PSFrameDemuxerCallback
{
public:
	virtual void OnVideoFrame(const unsigned char* pszBuffer, unsigned bufferSize, int streamType, unsigned timestamp)
	{
		WriteFile::GetInstans().W2File((char*)"my_264.264", (char*)(pszBuffer), bufferSize);
		g_ps_frame_my++;
		printf("################### g_ps_frame_my:%d \n", g_ps_frame_my);
	}
	virtual void OnAudioFrame(const unsigned char* pszBuffer, unsigned bufferSize, int streamType, unsigned timestamp)
	{
		WriteFile::GetInstans().W2File((char*)"my_pcm.722_1", (char*)(pszBuffer), bufferSize);
		g_OnAudioFrame_count++;
		printf("############# OnAudioFrame bufferSize:%d g_OnAudioFrame_count:%d \n ", bufferSize, g_OnAudioFrame_count);
	}
};

int main()
{

	CRtpManage tCRtpManage;
	int ret = tCRtpManage.init("uag_ps.pcap");
	printf("init ret:%d \n", ret);
	std::list<shared_ptr<rtpPacket> > olistRtp;
	tCRtpManage.getList(olistRtp);

	map<unsigned int, shared_ptr<rtpPacket> > oMapRtp;
	tCRtpManage.getMap(oMapRtp);


	uint32_t m_ts = 0;
	int32_t psLen = 0;

	
	std::vector<char> tBuffer;
	tBuffer.resize(1024 * 1024 * 10);
	char* m_chpsBuf = tBuffer.data();

	PSFrameDemuxerCallbackImp tPSFrameDemuxerCallbackImp;
	PsFrameDemuxer*  m_dumuxer = new PsFrameDemuxer(&tPSFrameDemuxerCallbackImp);
	int32_t m_bufOffset = 0;
#if 0
	for (std::list<shared_ptr<rtpPacket> >::iterator it = olistRtp.begin(); it != olistRtp.end(); it++)
	{

		shared_ptr<rtpPacket> pkt = *it;
#else
	for (std::map<unsigned int, shared_ptr<rtpPacket> >::iterator it = oMapRtp.begin(); it != oMapRtp.end(); it++)
	{

		shared_ptr<rtpPacket> pkt = it->second;

#endif
		printf("### key:%d len:%d \n", it->first, pkt->getPktLen());
		RTPHeader header;


		bool re = rtpParse(header, pkt->getHeader(), pkt->getPktLen());

		int32_t len = pkt->getPktLen();
		if (re)
		{
			uint32_t ts = header.timestamp;
			if (m_ts != ts)
			{
				if (m_bufOffset)
				{
					m_dumuxer->OnPsFrame((unsigned char*)&m_chpsBuf[0], m_bufOffset, m_ts);
				}
				m_ts = ts;
				m_bufOffset = 0;
			}
			psLen = len - header.headerLength;
			memcpy(&m_chpsBuf[0] + m_bufOffset, pkt->getHeader() + header.headerLength, psLen);
			m_bufOffset += psLen;

		}
	}

	getchar();

}

